package cn.nuc.edu.onlinestore.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import cn.nuc.edu.onlinestore.entity.Goods;
import cn.nuc.edu.onlinestore.entity.SysFunction;
import cn.nuc.edu.onlinestore.entity.Sysrole;
import cn.nuc.edu.onlinestore.entity.Sysuser;
import cn.nuc.edu.onlinestore.service.interfaces.IGoodsService;
import cn.nuc.edu.onlinestore.service.interfaces.IRoleService;
import cn.nuc.edu.onlinestore.service.interfaces.IUserService;
import cn.nuc.edu.onlinestore.util.PageControl;
import cn.nuc.edu.onlinestore.util.Pager;

/**
 * 用户handler
 * @author 王凯
 *
 */
@Controller
@RequestMapping("/user")
public class UserHandler {

	/**
	 * 用户业务逻辑
	 */
	@Autowired
	private IUserService userService;
	
	/**
	 * 角色业务逻辑
	 */
	@Autowired
	private IRoleService roleService;
	
	/**
	 * 商品业务逻辑
	 */
	@Autowired
	private IGoodsService goodsService;
	
	/**
	 * 管理员登录后台
	 */
	@RequestMapping("/backward")
	public String initbackwardlogin() {
		
		return "forward:/WEB-INF/views/login.jsp";
	}
	
	/**
	 * 用户注册，只能注册为普通用户
	 */
	@RequestMapping("/regist")
	public ModelAndView regist(Sysuser user, ModelAndView modelAndView) {
		
		//查出普通用户的roleid
		Sysrole role = new Sysrole();
		role.setRolename("普通用户");
		role = roleService.detail(role);
		user.setRoleid(role.getRoleid());
		
		//将新注册的用户注册成普通用户
		Integer rtn = userService.add(user);
		if(rtn > 0){
			modelAndView.setViewName("redirect:/login.jsp");
		}else{
			modelAndView.setViewName("redirect:/regist.jsp");
		}
		return modelAndView;
	}
	
	/**
	 * 用户添加（管理员）可以添加任何类型的用户
	 */
	@RequestMapping("/add")
	public ModelAndView add(Sysuser user, ModelAndView modelAndView) {
		//执行添加用户的逻辑
		Integer rtn = userService.add(user);
		
		//根据操作结果跳转到不同的页面
		if(rtn > 0){
			modelAndView.setViewName("redirect:/user/users");
		}else{
			modelAndView.addObject("msg", "新建用户失败");
			modelAndView.setViewName("forward:/WEB-INF/views/user/add.jsp");
		}
		return modelAndView;
	}

	/**
	 * 添加用户之前初始化角色下拉列表框的数据
	 */
	@RequestMapping("/toadd")
	public ModelAndView toadd(ModelAndView modelAndView) {
		
		//查询全部角色（不包含禁用的）
		List<Sysrole> rolelist =  roleService.listAll();
		
		//将结果集保存到request范围内
		modelAndView.addObject("rolelist", rolelist);
		
		//设置跳转逻辑
		modelAndView.setViewName("forward:/WEB-INF/views/user/add.jsp");
		return modelAndView;
	}

	/**
	 * 修改角色信息
	 * 
	 */
	@RequestMapping("/edit")
	public ModelAndView edit(Sysuser user, ModelAndView modelAndView) {
		
		//调用业务层的编辑逻辑
		Integer rtn = userService.edit(user);
		if (rtn > 0) {
			modelAndView.setViewName("redirect:/user/users");
		} else {
			modelAndView.addObject("msg", "保存用户信息失败！");
			modelAndView.setViewName("forward:/WEB-INF/views/user/edit.jsp");
		}
		return modelAndView;
	}
	
	/**
	 * 初始化修改页面
	 * 
	 */
	@RequestMapping("/toedit/{id}")
	public ModelAndView toedit(
				@PathVariable("id") Integer id, 
				ModelAndView modelAndView){

		//查询用户的详细信息
		Sysuser user = new Sysuser();
		user.setUserid(id);
		user = userService.detail(user);
		
		//如果用户存在
		if (user != null) {
			//调出角色列表（不包含禁用的）
			List<Sysrole> rolelist =  roleService.listAll();
			
			//保存用户信息和角色列表到request范围内
			modelAndView.addObject("item", user);
			modelAndView.addObject("rolelist", rolelist);
			
			//跳转
			modelAndView.setViewName("forward:/WEB-INF/views/user/edit.jsp");
		} else {
			modelAndView.addObject("msg", "需要修改的角色不存在。");
			modelAndView.setViewName("forward:/user/users");
		}
		return modelAndView;
	}
	
	/**
	 * 分页查询用户信息
	 * @param request
	 * @param response
	 */
	@RequestMapping("/users{currindex}")
	public ModelAndView list(String keyword, 
			@PathVariable(value = "currindex", required = false) Integer currindex,
			ModelAndView modelAndView) {
		
		//设置分页所需参数
		PageControl pc = new PageControl();
		if (currindex == null) {
			currindex = 1;
		}
		pc.setCurrentindex(currindex);
		pc.setPagesize(10);
		
		//设置关键字
		if (keyword != null && (!keyword.equals(""))) {
			keyword = "%" + keyword + "%";
		} else {
			keyword = null;
		}
		
		//保存分页结果集
		Pager<Sysuser> pager = userService.list(pc, keyword);
		modelAndView.addObject("pager", pager);
		
		//跳转
		modelAndView.setViewName("forward:/WEB-INF/views/user/list.jsp");
		
		return modelAndView;
	}
	
	/**
	 * 初始化改密码界面（界面受WEB-INF保护）
	 * @param modelAndView
	 * @return
	 */
	@RequestMapping("/initAlterPassword")
	public ModelAndView initAlterPassword(ModelAndView modelAndView) {
		modelAndView.setViewName("forward:/WEB-INF/views/user/alterPassword.jsp");
		return modelAndView;
	}

	/**
	 * 用户修改密码
	 * @param request
	 * @param response
	 */
	@RequestMapping("/alterPassword")
	public ModelAndView alterPassword(String oldpass, String newpass,
			HttpSession session, ModelAndView modelAndView) {
		
		//从session中取出已登录用户的信息
		Sysuser user =  (Sysuser) session.getAttribute("user");
		Integer userid = user.getUserid();	
		
		//执行修改密码的业务逻辑
		int rtn = userService.alterPassword(oldpass, newpass, userid);
		
		//根据操作结果跳转
		if (rtn > 0) {
			modelAndView.setViewName("redirect:/welcome.jsp");
		} else {
			modelAndView.addObject("msg", "修改密码失败！您可能没有正确的输入旧密码，亦或是系统出现错误！");
			modelAndView.setViewName("forward:/alterPassword.jsp");
		}
		return modelAndView;
	}

	/**
	 * 注销
	 * 
	 */
	@RequestMapping("/logout")
	public String logout(Map<String, Object> map, HttpSession session){

		//移除登录用户的信息
		session.removeAttribute("user");
		
		//session注销
		session.invalidate();
		
		//重定向到登录界面，丢掉所有请求信息
		return "redirect:/login.jsp";
	}

	/**
	 * 初始化主页
	 * 
	 */
	@RequestMapping("/initpage")
	public String initpage(HttpSession session, Model model) {

		//取出当前登录用户的信息
		Sysuser user = (Sysuser) session.getAttribute("user");
		
		//按用户的角色权限加载相匹配的功能列表
		List<SysFunction> list = userService.initpage(user);
		
		//保存列表
		model.addAttribute("list", list);
		return "forward:/WEB-INF/views/index.jsp";
	}
	
	/**
	 * 用户登陆(前台)
	 * 
	 */
	@RequestMapping("/login")
	public String login(String username, String userpwd,
			Map<String, Object> map,HttpSession session){

		//接收用户名和密码
		Sysuser user = new Sysuser();
		user.setUsername(username);
		user.setUserpwd(userpwd);

		//执行登录逻辑
		user = userService.login(user);
		
		//根据结果跳转
		if (user == null) {
			return "redirect:/login.jsp";
		} else {
			map.put("user", user);
			session.setAttribute("user", user);
			return "forward:/index";
		}
	}
	
	/**
	 * 得到消费记录
	 * 前台只能看到自己的记录
	 * 后台可以看到所有记录
	 * 
	 */
	@RequestMapping("/getConsumerList{opt}")
	public String getConsumerList(
			@PathVariable(value = "opt", required = false) Integer opt,
			Map<String, Object> map,
			HttpSession session){

		if (opt == 1) {  //前台
			//从session中取出登陆的user
			Sysuser user = (Sysuser) session.getAttribute("user");
			List<Goods> list = goodsService.getConsumerList(user);
			map.put("list", list);
			return "forward:/WEB-INF/views/record/listforuser.jsp";
		} else { //后台
			List<Goods> list = goodsService.getConsumerList(new Sysuser());
			map.put("list", list);
			return "forward:/WEB-INF/views/record/listforback.jsp";
		}
	}
	
	/**
	 * 分页查询用户信息（充值）
	 * @param request
	 * @param response
	 */
	@RequestMapping("/getchargelist{currindex}")
	public ModelAndView getchargelist(String keyword, 
			@PathVariable(value = "currindex", required = false) Integer currindex,
			ModelAndView modelAndView) {
		
		//设置分页参数
		PageControl pc = new PageControl();
		if (currindex == null) {
			currindex = 1;
		}
		pc.setCurrentindex(currindex);
		pc.setPagesize(10);
		
		//设置关键字
		if (keyword != null && (!keyword.equals(""))) {
			keyword = "%" + keyword + "%";
		} else {
			keyword = null;
		}

		//执行分页查询逻辑并保存结果集到request
		Pager<Sysuser> pager = userService.list(pc, keyword);
		modelAndView.addObject("pager", pager);
		
		modelAndView.setViewName("forward:/WEB-INF/views/user/chargelist.jsp");
		
		return modelAndView;
	}
	
	/**
	 * 初始化充值页面
	 * 
	 */
	@RequestMapping("/initcharge/{id}")
	public String initcharge(Map<String, Object> map,
			@PathVariable("id") Integer userid){

		//获得用户的详细信息
		Sysuser user = new Sysuser();
		user.setUserid(userid);
		user = userService.detail(user);
		
		//将用户详细信息保存到request中
		map.put("item", user);
		
		//跳转
		return "forward:/WEB-INF/views/user/charge.jsp";
	}
	
	/**
	 * 得到消费记录
	 * 
	 */
	@RequestMapping("/charge")
	public String charge(Map<String, Object> map, HttpSession session,
			@RequestParam("userid") Integer userid,
			@RequestParam("charge") Float charge){

		//执行充值逻辑
		userService.accountCharge(userid, charge);
		
		//跳转
		return "forward:/user/getchargelist";
	}
}
